var express = require('express');
var router = express.Router();
// 引入xss
var xss = require("xss");
//建立一个连接池
const {query} = require("../config/mysqlpool");

function restdata(code,msg) {
    return {
        code : code,
        msg:msg
    }
}
//注册
router.post('/register', function (req, res) {
    var username = xss(req.body.username)
    var password = xss(req.body.password)
    // console.log(xss(req.body.username))
    // console.log(xss(req.body.password))
    query("insert into `users` ( `username`, `password`) values (?,?)",[username,password],function (err,vals,filed) {
        console.log(1)
        console.log(filed)
        console.log(2)
        console.log(vals)
        console.log(err)
        if (err) {
            res.json(restdata(400,err))
        }else {
            res.json(restdata(200,"注册成功"))
        }
    })
});
//登入验证
router.post('/login', function (req, res) {
    var username = xss(req.body.username)
    var password = xss(req.body.password)
    console.log(xss(req.body.username))
    console.log(xss(req.body.password))
    query("select password,user_id from users where username = ? ",username,function (err,vals) {
        console.log("youzhima",vals)
        if (err){
            res.json({code: 400, msg: err})
        }else{
            if(vals[0]) {
                if (vals[0].password === password) {
                    res.json({code: 200, msg: 'success', user_id: vals[0].user_id})
                } else {
                    res.json({code: 400, msg: err})
                }
            }else{
                res.json({code: 400, msg: '登入失败'})
            }
        }
    })
});


module.exports = router;
